import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/components/calendar_btn_icon.dart';
import 'package:share_fit/app/components/date_type_bar.dart';
import 'package:share_fit/app/components/table_calendar_dialog.dart';
import 'package:share_fit/app/controllers/home/spo2/components/spo2_line_chart.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/date_type_enum.dart';
import 'package:share_fit/app/models/home/spo2_model.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'logic.dart';

class Spo2Page extends StatelessWidget {
  Spo2Page({super.key});

  final logic = Get.find<Spo2Logic>();
  final state = Get.find<Spo2Logic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F9FC),
      appBar: AppBar(
        leading: BackBtnIcon(onTap: () => Get.back()),
        actions: [
          GetBuilder<Spo2Logic>(
            id: 'calendar_btn_icon',
            builder: (_) {
              return _.state.selectedDateType.value == DateType.day
                  ? CalendarBtnIcon(
                      calenderDay: _.state.selectedDate,
                      onTap: () => _showDatePicker(context),
                    )
                  : Container();
            },
          ),
        ],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: ListView(
          children: [
            SizedBox(height: 60.h),
            GetBuilder<Spo2Logic>(
              id: 'date_type_bar',
              builder: (ctrl) => DateTypeBar(
                initIndex: ctrl.state.dateTypeBarIndex,
                onSelectChanged: (index, dateType) => ctrl.changeDateType(selectedIndex: index, type: dateType),
              ),
            ),
            SizedBox(height: 60.h),
            _buildCalendarContainer(),
            SizedBox(height: 60.h),
            _buildSummary(),
            SizedBox(height: 60.h),
            _buildChartContainer(),
            SizedBox(height: 60.h),
            _buildDetailContainer(),
            SizedBox(height: 60.h),
            _buildSpo2Tips(),
            SizedBox(height: 80.h),
          ],
        ),
      ),
    );
  }

  _buildCalendarContainer() {
    return GetBuilder<Spo2Logic>(
      id: 'sleep_date_range',
      builder: (ctrl) => Container(
        alignment: Alignment.center,
        child: Text(ctrl.state.dateRangeText),
      ),
    );
  }

  _buildDetailContainer() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 50.h, horizontal: 20.w),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.all(Radius.circular(60.r))),
      child: GetBuilder<Spo2Logic>(
        id: 'dataDetail',
        builder: (_) => Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Column(
              children: [
                Text(LocaleKeys.stress_avg_pressure_value_text.ts),
                Text(_.state.dataDetail['avg_oxygen_value']),
              ],
            ),
            Column(
              children: [
                Text(LocaleKeys.stress_min_pressure_value_text.ts),
                Text(_.state.dataDetail['min_oxygen_value']),
              ],
            ),
            Column(
              children: [
                Text(LocaleKeys.stress_max_pressure_value_text.ts),
                Text(_.state.dataDetail['max_oxygen_value']),
              ],
            ),
          ],
        ),
      ),
    );
  }

  _buildChartContainer() {
    return Container(
      height: 650.h,
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
      child: GetBuilder<Spo2Logic>(
        id: 'spo2_avg_list',
        builder: (_) => Spo2LineChart(summaryList: _.state.spo2AvgList.oxygenAvgs),
      ),
    );
  }

  Widget _buildSummary() {
    return Container(
      constraints: BoxConstraints.expand(height: 260.w),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(LocaleKeys.widgets_blood_oxygen.ts, style: TextStyle(fontSize: 48.sp)),
          GetBuilder<Spo2Logic>(
            id: 'spo2_summary',
            builder: (_) => Text(_.state.summary, style: TextStyle(fontSize: 120.sp)),
          ),
        ],
      ),
    );
  }

  Widget _buildSpo2Tips() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 50.h, horizontal: 50.w),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(60.r)),
      // constraints: BoxConstraints.expand(height: 530.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(LocaleKeys.spo2_tip_title.ts, style: TextStyle(fontSize: 42.sp, color: Colors.grey)),
          SizedBox(height: 30.h),
          Text(LocaleKeys.spo2_tip_content_text.ts, style: TextStyle(fontSize: 40.sp, color: Colors.grey)),
        ],
      ),
    );
  }

  String getTime(String formattedString) {
    if (formattedString.isEmpty) {
      return '00:00';
    }
    DateTime dateTime = DateTime.parse(formattedString);
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  String getDate(String formattedString) {
    if (formattedString.isEmpty) {
      return '';
    }
    DateTime dateTime = DateTime.parse(formattedString);
    return '${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')}';
  }

  List<BarChartGroupData> getBargroups() {
    List<BarChartGroupData> items = [];
    List<Spo2Summary> spo2Avgs = state.spo2AvgList.oxygenAvgs;
    for (int i = 0; i < spo2Avgs.length; i++) {
      Spo2Summary spo2 = spo2Avgs[i];

      List<BarChartRodData> rods = [];
      BarChartRodData barChartRodData = BarChartRodData(
        toY: spo2.oxygenValue.toDouble(),
        gradient: const LinearGradient(
          colors: [Color(0xFF1CEABD), Color(0xFF1CEABD)],
          begin: Alignment.bottomCenter,
          end: Alignment.topCenter,
        ),
        borderRadius: BorderRadius.zero,
      );
      rods.add(barChartRodData);

      BarChartGroupData barChartGroupData = BarChartGroupData(x: i, barRods: rods);
      items.add(barChartGroupData);
    }

    return items;
  }

  Widget bottomTitleWidgets(double value, TitleMeta meta) {
    TextStyle style = TextStyle(color: ColorConst.secondaryFontColor, fontSize: 36.sp);
    Widget text;
    switch (value.toInt()) {
      case 0:
        text = Container(
          margin: EdgeInsets.only(left: 57.w),
          child: Text('00:00', style: style),
        );
        break;
      case 10:
        text = Text('12:00', style: style);
        break;
      case 23:
        text = Container(
          margin: EdgeInsets.only(right: 57.w),
          child: Text('24:00', style: style),
        );
        break;
      default:
        text = Text('', style: style);
        break;
    }

    return SideTitleWidget(
      axisSide: meta.axisSide,
      child: text,
    );
  }

  /// 点击右上角日历图标，打开日历选择
  _showDatePicker(BuildContext context) {
    Get.dialog(
      TableCalendarDialog(
        onEvenLoad: (day) => logic.loadEventForDay(day),
      ),
      barrierColor: Colors.black.withOpacity(.8),
    ).then((value) => logic.datePicker(value));
  }
}
